package com.devdroids.cursortable;

import android.content.Context;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.CursorAdapter;
import android.widget.TableLayout;

public class CursorTableLayout extends TableLayout {
	
	private static final String tag = CursorTableLayout.class.getName();

	private CursorAdapter cursorAdapter;
	
	
	public CursorTableLayout(Context context) {
		super(context);
	}

	public CursorTableLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void setAdapter(CursorAdapter cursorAdapter) {
		this.cursorAdapter = cursorAdapter;
		if ( cursorAdapter != null ) {
            //dataSetObserver = new AdapterDataSetObserver();
            cursorAdapter.registerDataSetObserver(dataSetObserver);
            addViewsFromAdaptor();
		}
	}
	
	private void addViewsFromAdaptor() {
		if (cursorAdapter != null ) {
			Cursor cursor = cursorAdapter.getCursor();
			cursor.moveToFirst();
			for ( int i = 0; cursor.moveToPosition(i); i++ ) {
				this.addView(cursorAdapter.newView(getContext(), cursor, this));
			}
		}
	}
	
	private DataSetObserver dataSetObserver = new DataSetObserver() {

		@Override
		public void onChanged() {
			super.onChanged();
			Log.i(tag, "DataSetObserver onChanged!");
		}

		@Override
		public void onInvalidated() {
			super.onInvalidated();
			Log.i(tag, "DataSetObserver onInvalidated!");
		}

	}; 
}
